const Ajv = require('ajv')
const ajv = new Ajv({
  allErrors: true,
  jsonPointers: true
}) // options can be passed, e.g. {allErrors: true}
var localize = require('ajv-i18n')
const schema = {
  type: 'object',
  properties: {
    name: {
      type: "string",
      // test: true,
      errorMessage: "这是不对的",
      minLength: 10
    },
    age: {
      type: "number"
    },
    pets: {
      type: 'array',
    },
    isWorker: {
      type: 'boolean'
    }
  },
  required: ['name', 'age']
}
require('ajv-errors')(ajv)
ajv.addKeyword('test', {
  // compile(sch, parentSchema) {
  //   console.log(sch, parentSchema)
  //   return () => true
  // },
  // metaSchema: {
  //   type: 'boolean',
  // },
  macro(schema, parentSchema) {
    return {
      minLength: 10
    }
  },
  validate: function fun(schema, data) {
    // console.log(schema, data)
    fun.errors = [{
      instancePath: '/name',
      schemaPath: '#/properties/name/test',
      keyword: 'test',
      params: {},
      message: '总是校验不通过的'
    }]
    return false;
  }
})

//生成schema校验规则
const validate = ajv.compile(schema)

const data = {
  name: 'jokcy',
  age: 18,
  pets: ['mimi', 'wangcai'],
  isWorker: true
}
// 校验数据是否符合规则
const valid = validate(data)
if (!valid) {
  localize.zh(validate.errors);
  console.log(validate.errors)
}